package com.zhou;

import com.zhou.dto.Person;
import com.zhou.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@EnableAutoConfiguration
@RestController
@CrossOrigin // So that javascript can be hosted elsewhere
@ComponentScan(value = {"com.zhou.service", "com.zhou.config"})
@EnableAsync
public class Frontend {

    private static final Logger logger = LoggerFactory.getLogger(Frontend.class);

    @Autowired
    RestTemplate restTemplate;

  String backendBaseUrl = System.getProperty("spring.example.backendBaseUrl", "http://localhost:9000");

  @RequestMapping("/") public String callBackend() {
      if (1 == 1) {
          throw new RuntimeException("test1");
      }
    return restTemplate.getForObject(backendBaseUrl + "/api", String.class);
  }

    @Autowired
    private TestService testService;

    @PostMapping("/test")
    public Person test(@RequestBody Person person) {
        logger.info("{}", person);
        testService.testAsync(person);
        restTemplate.getForObject(backendBaseUrl + "/api", String.class);
        return person;
    }

    @Bean
    RestTemplate restTemplate() {
    return new RestTemplate();
  }

  public static void main(String[] args) {
    SpringApplication.run(Frontend.class,
        "--spring.application.name=frontend",
        "--server.port=8081"
    );
  }
}
